package cn.maydaymemory.maydaycore.command.api;

import cn.maydaymemory.maydaycore.configuration.LanguageManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class SuperCommand extends Command {
    private CommandStructureExecutor executor;
    public SuperCommand(String name, CommandStructure structure){
        super(name);
        changeStructure(structure);
    }
    @Override
    public boolean execute(CommandSender sender, String label, String[] args) {
        executor.sender(sender);
        //执行命令
        if(args.length<1&&executor.helperEnable()){
            executor.sendHelp(1);
            return true;
        }
        if(args.length==1){
            executor.excute(args[0],label,new String[0]);
            return true;
        }
        if(args.length>1){
            String[] par = new String[args.length - 1];
            System.arraycopy(args, 1, par, 0, args.length - 1);
            executor.excute(args[0],label,par);
            return true;
        }
        return true;
    }
    public SuperCommand changeStructure(CommandStructure structure){
        executor=new CommandStructureExecutor(structure)
                .changeHelperPrefix("/"+this.getName()+" ")
                .changeHelperTitle("§7"+this.getName()+"'s help");
        return this;
    }
    public CommandStructureExecutor executor(){ return executor;}

    public SuperCommand language(LanguageManager language){
        executor.language(language);
        return this;
    }
    public LanguageManager language(){
        return executor.language();
    }
    @Override
    public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
        CommandStructureExecutor executor = this.executor;
        if(args[0].equals("")){
            return executor.complete();
        }
        boolean find = false;
            for(String arg : args){
                try {
                    CommandStructure structure =executor.getChildStructure(arg);
                    if(structure!=null){
                        executor = structure.getChildStructureExecutor(structure);
                        find=true;
                    }
                } catch (InvocationTargetException | IllegalAccessException ignore) { }
            }
        if (find)
            return executor.complete();
        else return new ArrayList<>();
    }
}
